//
//  ActivityEnrollViewController.m
//  homeland
//
//  Created by gzbugu on 14-8-4.
//  Copyright (c) 2014年 xzysun. All rights reserved.
//

#import "ActivityEnrollViewController.h"
#import "UIImageView+WebCache.h"
#import "NoticesItem.h"
#import "UserInfoService.h"
#import "CheckButton.h"
#import "RadioGroup.h"
#import "XHImageViewer.h"
#import "VoteMasterDetailViewController.h"
#import "SurveyDetailViewController.h"
#import "SurveyItemEntity.h"
#import "VoteMasterEntity.h"
#import <QuartzCore/QuartzCore.h>

//扩展属性
@interface ActivityEnrollViewController () <XHImageViewerDelegate> {
    //当前页面－图片集
    NSMutableArray *_imageViews;
    //手势识别事件
    UITapGestureRecognizer *_gesture;
}
//变量区
//=========================
//定义一个变量来记录下一个将要添加的控件的位置
@property (assign, nonatomic) int nextY;
//调查主体id
@property (strong, nonatomic) NSString *masterId;
//是否投过票
@property (assign, nonatomic) NSInteger countNum;
//是否结束
@property (assign, nonatomic) NSInteger isEnd;
//模块名称
@property (strong, nonatomic) NSString *typeStr;
@end

@implementation ActivityEnrollViewController
//方法区
//=========================
-( id )initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self =[ super initWithNibName :nibNameOrNil bundle :nibBundleOrNil];
    if (self){
        
    }
    return self ;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"活动报名";
    [self configView];
}

/**数据渲染展示*/
-(void)configView{
    _nextY = 0;
    _imageViews = [NSMutableArray array];
    //主体内容展示
    //--------------------------
    NoticesItem *item = [_config objectForKey:@"dataItem"];
    _masterId = [CommonUtil dealNullObject:item.Id];
    //是否结束，等于零表示过期
    _isEnd = (NSNull *)item.isEnd == [NSNull null] ?1:[CommonUtil dealNullObject:item.isEnd].intValue;
    //模块名称
    _typeStr = [CommonUtil dealNullObject:item.type];
    
    //展示主体内容
    //-------------------
    NSString *typeStr2 = [[@"【" stringByAppendingString:_typeStr] stringByAppendingString:@"】"];
    NSString *_Vtitle = [typeStr2 stringByAppendingString:[CommonUtil dealNullObject:item.title]];
    //根据内容调整高度
    CGFloat titleHeight = [self caculateHeightForString:_Vtitle AndFontSize:16.0f AndWitdh:300.0f];
    
    self.titleTextView.frame = CGRectMake(self.titleTextView.frame.origin.x,self.titleTextView.frame.origin.y, self.titleTextView.frame.size.width, titleHeight);
    self.titleTextView.text = _Vtitle;
    
    //展示图片
    //--------------------
    NSString *pic = [CommonUtil dealNullObject:item.picture];
    if (![pic equals:@""]) {
        pic= [NSString stringWithFormat:@"http://%@%@", SERVER_URL_COMMUNITY_NOTICE_IMAGE, item.picture];
        self.imageView.frame = CGRectMake(self.imageView.frame.origin.x,CGRectGetMaxY(self.titleTextView.frame) + 5.0, self.imageView.frame.size.width, self.imageView.frame.size.height);
        __block UIActivityIndicatorView *activityIndicator;
        __weak UIImageView *weakImageView = self.imageView;
        [self.imageView setImageWithURL:[NSURL URLWithString:pic] placeholderImage:[UIImage imageNamed:@"placeholder.png"] options:SDWebImageProgressiveDownload progress:^(NSUInteger receivedSize, long long expectedSize){
            if (!activityIndicator){
                [weakImageView addSubview:activityIndicator = [UIActivityIndicatorView.alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]];
                activityIndicator.center = weakImageView.center;
                [activityIndicator startAnimating];
            }
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType){
            [activityIndicator removeFromSuperview];
            activityIndicator = nil;
        }];
        //用于给图片绑定事件
        _gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHandle:)];
        self.imageView.userInteractionEnabled = YES;
        self.imageView.contentMode = UIViewContentModeScaleAspectFill;
        self.imageView.clipsToBounds = YES;
        [self.imageView addGestureRecognizer:_gesture];
        
        [_imageViews addObject:self.imageView];
        
        //间隔线
        self.spiritLine.frame = CGRectMake(self.spiritLine.frame.origin.x, CGRectGetMaxY(self.imageView.frame)+5.0,self.spiritLine.frame.size.width, 0.5);
    }else{
        self.imageView.hidden = YES;
        
        //间隔线
        self.spiritLine.frame = CGRectMake(self.spiritLine.frame.origin.x, CGRectGetMaxY(self.titleTextView.frame)+5.0,self.spiritLine.frame.size.width, 0.5);
    }
    UserInfoService *userInfo=[UserInfoService getUserInfoService];

    self.userNameText.text = [CommonUtil dealNullObject:userInfo.userInfo.nickName];
    self.communityNameText.text = [CommonUtil dealNullObject:[_tempConfig objectForKey:@"communityName"]];
    self.contentPanel.frame =CGRectMake(self.contentPanel.frame.origin.x, CGRectGetMaxY(self.spiritLine.frame)+5.0,self.contentPanel.frame.size.width, self.contentPanel.frame.size.height);
    
    _nextY+= (CGRectGetMaxY(self.contentPanel.frame) + 30.0);//下一元素显示的位置
    
    //创建按钮
    [self createBtn];
    
    CGFloat totalHeight = MAX(_nextY, CGRectGetHeight(self.scrollView.frame));
    self.mainPanel.frame = CGRectMake(0.0, 0.0, 320.0, totalHeight);
    [self.scrollView addSubview:self.mainPanel];
    self.scrollView.contentSize = self.mainPanel.frame.size;
}

/**
 *创建按钮
 */
- (void)createBtn{
    int height = iPhone5 ? 0 : 88 ;
    //生成底部按扭-
    if ([_typeStr isEqualToString:@"活动报名"]) {
        if (_isEnd == 0) {//已结束
            UIButton *endBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 460 - height, 320, 44)];
            [endBtn setBackgroundImage:[UIImage imageNamed:@"black_line.jpg"] forState:0];
            [endBtn setTitle:@"已结束" forState:0];
            [endBtn addTarget:self action:@selector(endResult:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:endBtn];
        }else{
            UIButton *postBtn = [[UIButton alloc] initWithFrame:CGRectMake(0,460 - height, 320, 44)];
            [postBtn setBackgroundImage:[UIImage imageNamed:@"btnImage.png"] forState:0];
            [postBtn setTitle:@"完成报名" forState:0];
            [postBtn addTarget:self action:@selector(postResult:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:postBtn];
        }
    }
    
    _nextY+=20;
}

/**提交活动报名*/
- (void)postResult:(id) sender{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    UserInfoService *userInfo=[UserInfoService getUserInfoService];
    if ([params objectForKey:@"userId"]==nil) {
        [params setValue:userInfo.userInfo.Id forKey:@"userId"];
    }
    [params setValue:_masterId forKey:@"activitiesEnrollId"];
    NSString *userName = [CommonUtil dealNullObject:self.userNameText.text];
    NSString *communityName = [CommonUtil dealNullObject:self.communityNameText.text];
    NSString *doorNum = [CommonUtil dealNullObject:self.doorNumText.text];
    NSString *link = [CommonUtil dealNullObject:self.linkText.text];
    
    if ([userName equals:@""]) {
       [self.view makeToast:@"请输入姓名" duration:2.0 position:@"center"];
        return ;
    }else if([communityName equals:@""]){
        [self.view makeToast:@"请输入所在社区" duration:2.0 position:@"center"];
        return ;
    }else if([doorNum equals:@""]){
        [self.view makeToast:@"请输入门号" duration:2.0 position:@"center"];
        return ;
    }else if([link equals:@""]){
        [self.view makeToast:@"请输入联系方式" duration:2.0 position:@"center"];
        return ;
    }
    
    [params setValue:userName forKey:@"name"];
    [params setValue:communityName forKey:@"community"];
    [params setValue:doorNum forKey:@"roomNumber"];
    [params setValue:link forKey:@"phone"];
    
    //进行提交
    [self startLoadingViewWithText:@"正在报名..."];
     MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:SERVER_URL_ACTIVITIES_ENROLL_PEPOPLE customHeaderFields:nil];
        //请求服务端数据
        MKNetworkOperation *op = [currentEngine operationWithPath:@"" params:params httpMethod:@"POST"];
        [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
            //关闭提示加载框
            [self stopLoadingView];
            NSDictionary *json = [completedOperation responseJSON];
            NSString *tipStr = [CommonUtil dealNullObject:[json objectForKey:@"message"]];
                      tipStr = [tipStr equals:@""]?@"报名成功":tipStr;
            [self.view makeToast:tipStr duration:2.0 position:@"center"];
            
            //关闭当前页，返回上一层
        } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
            //关闭提示加载框
            [self stopLoadingView];
            [self.view makeToast:@"报名失败，请重新登录再操作" duration:2.0 position:@"center"];
        }];
        [currentEngine enqueueOperation:op];
}

/**提示已结束*/
- (void)endResult:(id) sender{
    NSString * tipStr = [NSString stringWithFormat:@"此次%@已结束，谢谢您的参与",_typeStr];
    [self.view makeToast:tipStr duration:2.0 position:@"center"];
}
//图片浏览事件
- (void)tapHandle:(UITapGestureRecognizer *)tap {
    XHImageViewer *imageViewer = [[XHImageViewer alloc] init];
    imageViewer.delegate = self;
    imageViewer.disableTouchDismiss = NO;
    [imageViewer showWithImageViews:_imageViews selectedView:(UIImageView *)tap.view];
}
- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
